#!/usr/bin/perl

# ---------- Init variables -------
#my $version = "0.0001";
# ---------- external readable parameters -------
## Functions
##-------------------------------------------------------
#
# stict syntax checking.
require Exporter;
use strict;
use SIM_settings;
use SIM_base;
use CGI qw(param);

#BEGIN { $Exporter::Verbose=1 }

# Startupscript translater
my $module = $ARGV[0];
my $tool = $ARGV[1];
my $action = $ARGV[2];
my $option1 = $ARGV[3];
my $option2 = $ARGV[4];
my $option3 = $ARGV[5];



my $backHeader="black";
my $httpUser = $ENV{'REMOTE_USER'};
my $httpReF = $ENV{'HTTP_REFERER'};
my $httpScriptName = $ENV{'SCRIPT_NAME'};
my $httpUserIp = $ENV{'REMOTE_ADDR'};
my $httpServerName = $ENV{'HTTP_HOST'};
my $httpCookie = $ENV{'HTTP_COOKIE'};
my $httpHost = $ENV{'HTTP_HOST'};
my $accessRightDir = $ENV{'SIM_ACCESSD'} || die "No env SIM_ACCESSD found.";
my $settingsDir = $SIMparam{'SIMsettingsDir'};
my $htaccessFile = $ENV{'SIM_HTTPPWDLIST'} || die "No env SIM_HTTPPWDLIST found.";
my $coloursFile = "$settingsDir/lessColors-$httpUser";
my $beepFile = "$settingsDir/simBeep-$httpUser";
my $accessSettingsFile = "$settingsDir/simAccessSettings-$httpUser";
my $showDebugFile = "$settingsDir/simShowDebug-$httpUser";

sub catFile {
  my $output = "";
  my ($file) = @_;
  open FH, $file or $output = "none";
# $output = readline FH;
  $output = <FH>;
  close FH;
  return $output;
}

sub catFileLine {
  my $outPut = "";
  my ($file) = @_;
  open FH, $file or $outPut = "$file";
  $outPut = <FH>;
  close FH;
  chomp($outPut);  # remove the newline
  return $outPut;
}

sub printFileLine {
  my $file = "@_[0]";
  my $varName = "@_[1]";
  my $rest = "@_[2]";
  my $logFile = "@_[3]";
  my $oldVal = catFileLine ("$file");
# print ("Update file=$file, varName=$varName, content:$rest<BR>");
  if ( "$oldVal" ne "$rest" ) {
    open(OUT, ">$file") || die "cannot create $file: $! (file=$file, varName=$varName, rest=$rest)";
    if ( "$logFile" ne "quiet" ) {
      print ("$varName is gewijzigd, oud:$oldVal nieuw:$rest.<BR>");
    }
    print OUT "$rest";
    close(OUT);
  }
}

sub testNameStrict {
  my $testname = "@_[0]";
  my $type = "@_[1]";
  if ( "$type" eq "word" ) {
    $testname =~ tr#a-zA-Z[\xE0][\xE8][\xEC][\xF2][\xF9]##cd;
  } else {
    $testname =~ tr#a-zA-Z0-9[\@][\.][\-]#A#cds;
  }
  #print ("testname=$testname");
  return $testname;
}

sub testMkDir {
  my $dirName = "@_[0]";
  if ( !-d $dirName ) {
    system "mkdir -p $dirName";
  }
}

sub readUpdParam {
  my $file = "@_[0]";
  my $name = "@_[1]";
  my $param = param("$name");
  if ( "$param" eq "" ) {
    $param = catFileLine("$file");
  } else {
    printFileLine("$file","$name","$param");
  }
  return $param;
}

sub userSettings {
  my ( $updLessColors, $updSimBeep );
  if ( -f $coloursFile ) {
    $updLessColors = "simple";
  } else {
    $updLessColors = "full";
  }
  if ( ! -f $beepFile ) {
    $updSimBeep = "beep";
  } else {
    $updSimBeep = catFileLine($beepFile);
  }
  print ("<HR><CENTER>
          <TABLE>
	  <TR><TD>Display color lines ($updLessColors)</TD>
	    <TD><A HREF=$httpScriptName?$module+$tool+updLessColors>Modify</A></TD>
	  <TR><TD>Allert on error ($updSimBeep)</TD><TD><FORM method=post Action=$httpScriptName?$module+$tool+updSimBeep>
	    <SELECT NAME=updSimBeep><OPTION VALUE=$updSimBeep>$updSimBeep</OPTION>
	      <OPTION VALUE=beep>beep</OPTION>
	      <OPTION VALUE=popup>popup</OPTION>
	      <OPTION VALUE=silent>silent</OPTION>
	    </SELECT>
	    <INPUT TYPE=submit Value=\"Modify allert\"></FORM></TD></TR>
          <TR><TD VALIGN=top>Change password</TD>
            <TD VALIGN=top><FORM method=post Action=$httpScriptName?$module+$tool+setPassword>
              <INPUT NAME=password1 Size=12 Type=password> again <INPUT NAME=password2 Size=12 Type=password>
              <INPUT TYPE=submit Value=\"Set password\">
            </FORM></TD>
            <TD>Please make sure this password complies to your local security standards</TD></TR>
          </TABLE>");
}

sub adminSettings {
  my ( $accessSettings, $showDebug );
  if ( -f $accessSettingsFile ) {
    $accessSettings = catFileLine( $accessSettingsFile );
  } else {
    $accessSettings = "no";
  }
  if ( -f $showDebugFile ) {
    $showDebug = catFileLine( $showDebugFile );
  } else {
    $showDebug = "no";
  }
  my $monDevices = catFileLine( $SIM_MonDevices );
  my $runCiscoTelnetPwds = catFileLine( $SIM_CiscoPwds);
  my $tftpBootDir = catFileLine( $SIM_TftpBootDir );
  printDebug(1, "settingsDir = $settingsDir");
  printDebug(1, "debugging = $debugging");
  print "<HR><CENTER>
         <TABLE>
	 <TR><TD>Currrent access setting set to \"$accessSettings\".</TD>
           <TD><A HREF=$httpScriptName?$module+$tool+setUpdLevel>Modify</A></TD>
	   <TD>Should we display the menu access-level tool($accessSettingsFile).</TD></TR>
         <TR><TD>Show debug set to \"$showDebug\".</TD>
           <TD><A HREF=$httpScriptName?$module+$tool+setShowDebug>Modify</A></TD>
           <TD>Should debug info be shown.</TD></TR>
	 <TR VALIGN=top><TD>Monitor devices.</TD>
	   <TD><FORM method=post Action=$httpScriptName?$module+$tool+setMonDevices>
	         <INPUT NAME=monDevices Size=50 VALUE=\"$monDevices\" Type=text>
	         <INPUT TYPE=submit Value=Set>
	       </FORM></TD>
	   <TD>What device types should be monitored in the monitor statusbar.</TD></TR>
	 <TR VALIGN=top><TD>Tftpboot directory.</TD>
	   <TD><FORM method=post Action=$httpScriptName?$module+$tool+setTftpBootDir>
	         <INPUT NAME=tftpBootDir Size=50 VALUE=\"$tftpBootDir\" Type=text>
	         <INPUT TYPE=submit Value=Set>
	       </FORM></TD>
	 </TABLE>";

}

sub setParam {
  my $param = "@_[0]";
  my $fileName = "@_[1]";
  my $value = param( $param );
  print ("<PRE>Setting param to $value in $fileName.</PRE>");
  printFileLine( $fileName, $param, $value );
  # test to verify content.
  # my $test = catFileLine( $fileName );
  # print("New val for $param in $fileName: $test");
}

sub setDispAccess {
  my $param1 = "@_[0]";
  my $param2 = "@_[1]";
  my $selectDispAccess = param('selectDispAccess');
  if ( "$selectDispAccess" ne "" ) {
    print ("Setting access level for action: $param1+$param2 to $selectDispAccess.");
    printFileLine( "$accessRightDir/$param1+$param2" , "$param1+$param2", $selectDispAccess );
  }
}

sub flipFile {
  my $settingsFile = "@_[0]";
  my $param = "@_[1]";
  if ( -f $settingsFile ) {
    print("Unlinking $param");
    unlink( $settingsFile );
  } else {
    printFileLine( $settingsFile, "$param", "yes" );
  }
}

sub setPassword {
  my $pwd1 = param('password1');
  my $pwd2 = param('password2');
  my $minLenght = 8;
  my $length = length( $pwd1 ); 
  #my $pwUcase = $pwd1;
  #$pwUcase =~ tr#A-Z#A#cds;
  my $pwLcase = $pwd1;
  $pwLcase =~ tr#a-z#A#cds;
  my $pwNum = $pwd1;
  $pwNum =~ tr#0-9#A#cds;
  
  if ( "$pwd1" ne "$pwd2" ) {
    print("Oops, the 2 passwords you entered are not identical, not updating.");
  } elsif ( "$length" < $minLenght ) {
    print("Oops, the length of your password is less than $minLenght characters, not updating ($length).");
  #} elsif ( "$pwUcase" eq "" ) {
  #  print("Oops, No uppercase charactes found in your password, not updating.");
  } elsif ( "$pwLcase" eq "" ) {
    print("Oops, No lowercase charactes found in your password, not updating.");
  } elsif ( "$pwNum" eq "" ) {
    print("Oops, No numbers charactes found in your password, not updating.");
  } else {
    my $time = time;
    $time = $time + 7776000;
    print("Updating password for user $httpUser.");
    system(" htpasswd -b $htaccessFile $httpUser $pwd1 ");
    printFileLine("$settingsDir/pwdUpdTime-$httpUser","pwdUpdTime","$time","quiet");
  }
}

sub testSettings {
  my $currtime = time;
  my $updTime = catFileLine("$settingsDir/pwdUpdTime-$httpUser");
  if (( ! -f "$settingsDir/pwdUpdTime-$httpUser" ) or ( "$currtime" > "$updTime" )) {
    print("<CENTER><H2><FONT COLOR=red>Please update your password....</FONT></H2>");
# } else {
#   print("currtime=$currtime, updTime=$updTime");
  }
}

sub updSimBeep {
  my $setting = param('updSimBeep');
  if ( "$setting" eq "beep" ) {
    unlink $beepFile;
  } else {
    printFileLine("$beepFile","allert",$setting);
  }
}


#--------------------------- Main ---------------------------

#print(" module=$module, tool=$tool, action=$action, option1=$option1, option2=$option2, option3=$option3.<BR>");
my $module = $ARGV[0];
my $tool = $ARGV[1];
my $action = $ARGV[2];
my $option1 = $ARGV[3];
my $option2 = $ARGV[4];
my $option3 = $ARGV[5];


if ( "$tool" eq "adminSettings" ) {
  if ( "$action" eq "setShowDebug" ) {
    flipFile($showDebugFile,"displayDebugInfo");
  } elsif ( "$action" eq "setUpdLevel" ) {
    flipFile($accessSettingsFile,"updateLevel");
  } elsif ( "$action" eq "setMonDevices" ) {
    setParam( "monDevices", $SIM_MonDevices );
  } elsif ( "$action" eq "setTftpBootDir" ) {
    setParam( "tftpBootDir", $SIM_TftpBootDir );
  } elsif ( "$action" eq "setDispAccess" ) {
    setDispAccess( $option1, $option2 );
  }
  adminSettings;
} elsif ( "$tool" eq "userSettings" ) {
  if ( "$action" eq "updLessColors" ) {
    flipFile($coloursFile,"lessColors");
  } elsif ( "$action" eq "updSimBeep" ) {
    updSimBeep;
  } elsif ( "$action" eq "setPassword" ) {
    setPassword;
  }
  testSettings;
  userSettings;
} else {
  print("Oops, tool coded ($tool).");
}
